import cloud from '@lafjs/cloud'
const dbm = cloud.mongo.db
let data
let dbName = "admin-class-signIn"

export default async function (ctx: FunctionContext) {
  data = ctx.body.data
  switch (ctx.body.type) {
    case "list":
      return list()
      break;
    case "signIn-history":
      return signInHistory()
      break;
    case "studentList":
      return studentList()
      break;
    case "setStatus":
      return setStatus()
      break;
    case "signInStudentsQuery":
      return signInStudentsQuery()
      break;
    case "update":
      return cloud.utils.updateData(dbName, data)
      break;
    case "add":
      return cloud.utils.addData(dbName, data)
      break;
    case "todayBeforeSignIn":
      return await todayBeforeSignIn()
      break;
    case "query":
      return query()
      break;
    default:
      break;
  }
}

//历史签到记录
async function signInHistory() {
  let query = { classId: data.classId, signInComplete: 1 }
  let aa = await dbm.collection("admin-teaching-schedule").find(query).sort({ dateStamp: 1 }).toArray()
  return cloud.utils.requestReturn({ data: aa })
}

//查询本日日期之前，还没有签到的排期
async function todayBeforeSignIn() {
  let arr = []
  let res = await dbm.collection("admin-teaching-schedule").find({ classId: data.classId }).toArray()
  res.forEach(element => {
    let dateStamp = cloud.utils.getTimeFn(element.date)
    let now = cloud.utils.getTimeFn()
    if ((dateStamp < now) && (!element.signInComplete)) arr.push(element)
  });
  return cloud.utils.requestReturn({ data: arr })
}

//自己设置查询条件
async function query() {
  let res = await dbm.collection(dbName).find(data).toArray()
  return cloud.utils.requestReturn({ data: res })
}

//该班次的学生签到了多少个
async function signInStudentsQuery() {
  let aa = await dbm.collection(dbName)
    .find({
      classId: data.classId,
      schedulingId: data.schedulingId,
    })
    .toArray()

  let bb = await dbm.collection("admin-class-student")
    .find({
      classId: data.classId,
      userState: 1,
    })
    .toArray()
  return cloud.utils.requestReturn({ data: aa.length >= bb.length })
}

// 设置签到状态
async function setStatus() {
  let whereJson = { ...data }
  delete whereJson.status
  let res = await cloud.nw.db.findByWhereJson({
    dbName, whereJson,
  });
  //编辑
  if (res && res._id) {
    await cloud.nw.db.update({
      dbName,
      whereJson,
      dataJson: { ...data, updatedAt: Date.now() }
    });
  } else {
    await cloud.nw.db.add({
      dbName,
      dataJson: data,
      cancelAddTime: false
    });
  }
  return cloud.utils.requestReturn({ data: "" })
}

async function studentList() {
  let res = await cloud.nw.db.selects({
    dbName: "admin-class-student",
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    // 主表 where 条件
    whereJson: {
      classId: data.classId,
    },
    // 主表排序规则
    sortArr: [
      { "name": "userState", "type": "desc" },
      { "name": "userPinyin", 'type': "asc" },
      { "name": "_add_time", "type": "asc" }
    ],
    // 副表列表
    foreignDB: [
      {
        dbName: "web-users",//副表 order
        localKey: "userId",
        foreignKey: "_id",
        as: "user_info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          baseInfo: 1
        },
      },
      {
        dbName: "admin-class-signIn",//副表 order
        localKey: "userId",
        foreignKey: "userId",
        as: "signIn_info",
        limit: 1,
        whereJson: {
          classId: data.classId,
          schedulingId: data.schedulingId,
        },
        // 副表字段显示规则
        fieldJson: {
          status: 1,
          remark: 1,
        },
      },
      {
        dbName: "admin-class-offline-student",//线下学员
        localKey: "offlineUserId",
        foreignKey: "_id",
        as: "user_data",
        limit: 1,
      },
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}

async function list() {
  let query = { classId: data.classId }
  const startOfYear = new Date(data.start).getTime(); // 该年份的开始时间戳
  const endOfYear = new Date(data.end).getTime(); // 该年份的结束时间戳
  query["dateStamp"] = { $gt: startOfYear, $lt: endOfYear }
  let aa = await dbm.collection("admin-teaching-schedule").find(query).sort({ sort: 1, dateStamp: 1 }).toArray()
  return cloud.utils.requestReturn({ data: aa })
}
